package xml;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 孙许
 * @date 2018-04-20
 * @description 用DOM方式读取xml文件
 */
public class ReadxmlByDom {

    private static final Logger logger = LogManager.getLogger(ReadxmlByDom.class);
    private static DocumentBuilderFactory factory;
    private static DocumentBuilder builder;

    static {
        try {
            factory = DocumentBuilderFactory.newInstance();
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
    }

    public List<Book> getBooks(File fileName) throws Exception {
        // 将指定的文件解析成xml文档
        Document document = builder.parse(fileName);
        // 获得所有Element名为book的元素
        NodeList bookList = document.getElementsByTagName("book");
        List<Book> books = new ArrayList<>();

        for (int i = 0; i < bookList.getLength(); i++) {
            Book book = new Book();
            Node node = bookList.item(i);
            // 获得第i个Book的所有属性
            NamedNodeMap attributes = node.getAttributes();
            // 获取名为id的属性
            String id = attributes.getNamedItem("id").getTextContent();
            book.setId(Integer.parseInt(id));

            // 获取book节点的子节点，包含Text类型的换行
            NodeList childNodes = node.getChildNodes();
            logger.debug("childNodes个数" + childNodes.getLength());

            ArrayList<String> contents = new ArrayList<>();
            for (int j = 0; j < childNodes.getLength(); j++) {
                Node childNode = childNodes.item(j);
                // 排除Text类型
                if (childNode instanceof Element) {
                    Text text = (Text) childNode.getFirstChild();
                    String strText = text.getData().trim();
                    contents.add(strText);
                }
            }

            book.setName(contents.get(0));
            book.setAuthor(contents.get(1));
            book.setYear(Integer.parseInt(contents.get(2)));
            book.setPrice(Double.parseDouble(contents.get(3)));
            books.add(book);
        }
        return books;
    }
}
